/* ===========================================
   管理端桌面端优化脚本
   =========================================== */

class DesktopOptimizer {
    constructor() {
        this.keyboardShortcuts = new Map();
        this.performanceMonitor = new PerformanceMonitor();
        this.init();
    }

    init() {
        this.setupKeyboardShortcuts();
        this.setupPerformanceOptimizations();
        this.setupDesktopEnhancements();
        this.setupErrorHandling();
        console.log('✅ 桌面端优化器已初始化');
    }

    /**
     * 设置键盘快捷键
     */
    setupKeyboardShortcuts() {
        // 全局快捷键
        this.registerShortcut('ctrl+1', () => this.navigateTo('dashboard.html'), '仪表盘');
        this.registerShortcut('ctrl+2', () => this.navigateTo('products.html'), '商品管理');
        this.registerShortcut('ctrl+3', () => this.navigateTo('orders.html'), '订单管理');

        this.registerShortcut('ctrl+5', () => this.navigateTo('reports.html'), '报表分析');
        
        // 功能快捷键
        this.registerShortcut('ctrl+s', () => this.saveCurrentPage(), '保存当前页面');
        this.registerShortcut('ctrl+f', () => this.focusSearch(), '聚焦搜索框');
        this.registerShortcut('ctrl+r', () => this.refreshPage(), '刷新页面');
        this.registerShortcut('ctrl+q', () => this.showQuickActions(), '快速操作');
        this.registerShortcut('ctrl+h', () => this.toggleSidebar(), '显示/隐藏侧边栏');
        
        // 监听键盘事件
        document.addEventListener('keydown', (e) => this.handleKeyboardShortcut(e));
        
        // 显示快捷键帮助
        this.showShortcutHelp();
    }

    /**
     * 注册快捷键
     */
    registerShortcut(combo, callback, description) {
        this.keyboardShortcuts.set(combo, { callback, description });
    }

    /**
     * 处理键盘快捷键
     */
    handleKeyboardShortcut(event) {
        const key = event.key.toLowerCase();
        let combo = '';

        if (event.ctrlKey || event.metaKey) {
            combo += 'ctrl+';
        }
        if (event.altKey) {
            combo += 'alt+';
        }
        if (event.shiftKey) {
            combo += 'shift+';
        }
        
        combo += key;

        const shortcut = this.keyboardShortcuts.get(combo);
        if (shortcut) {
            event.preventDefault();
            shortcut.callback();
            this.showShortcutFeedback(combo, shortcut.description);
        }
    }

    /**
     * 显示快捷键反馈
     */
    showShortcutFeedback(combo, description) {
        const feedback = document.createElement('div');
        feedback.className = 'shortcut-feedback';
        feedback.innerHTML = `
            <div style="
                position: fixed;
                top: 20px;
                right: 20px;
                background: rgba(52, 152, 219, 0.9);
                color: white;
                padding: 10px 15px;
                border-radius: 5px;
                font-size: 14px;
                z-index: 10000;
                animation: slideInRight 0.3s ease;
            ">
                <strong>${description}</strong> (${combo})
            </div>
        `;
        
        document.body.appendChild(feedback);
        
        setTimeout(() => {
            feedback.remove();
        }, 2000);
    }

    /**
     * 显示快捷键帮助
     */
    showShortcutHelp() {
        const helpButton = document.createElement('button');
        helpButton.innerHTML = '⌨️';
        helpButton.title = '键盘快捷键帮助';
        helpButton.style.cssText = `
            position: fixed;
            bottom: 20px;
            right: 20px;
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background: var(--primary-color);
            color: white;
            border: none;
            font-size: 18px;
            cursor: pointer;
            z-index: 9999;
            box-shadow: 0 4px 15px rgba(0,0,0,0.2);
            transition: all 0.3s ease;
        `;
        
        helpButton.addEventListener('mouseenter', () => {
            helpButton.style.transform = 'scale(1.1)';
            helpButton.style.boxShadow = '0 6px 20px rgba(0,0,0,0.3)';
        });
        
        helpButton.addEventListener('mouseleave', () => {
            helpButton.style.transform = 'scale(1)';
            helpButton.style.boxShadow = '0 4px 15px rgba(0,0,0,0.2)';
        });
        
        helpButton.addEventListener('click', () => this.showShortcutModal());
        
        document.body.appendChild(helpButton);
    }

    /**
     * 显示快捷键模态框
     */
    showShortcutModal() {
        const modal = document.createElement('div');
        modal.className = 'shortcut-modal';
        modal.innerHTML = `
            <div style="
                position: fixed;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background: rgba(0,0,0,0.5);
                display: flex;
                align-items: center;
                justify-content: center;
                z-index: 10000;
            ">
                <div style="
                    background: white;
                    border-radius: 10px;
                    padding: 30px;
                    max-width: 600px;
                    width: 90%;
                    max-height: 80vh;
                    overflow-y: auto;
                    box-shadow: 0 20px 60px rgba(0,0,0,0.3);
                ">
                    <h2 style="margin: 0 0 20px 0; color: var(--dark-color);">键盘快捷键</h2>
                    <div id="shortcut-list"></div>
                    <button onclick="this.parentElement.parentElement.remove()" style="
                        margin-top: 20px;
                        padding: 10px 20px;
                        background: var(--primary-color);
                        color: white;
                        border: none;
                        border-radius: 5px;
                        cursor: pointer;
                    ">关闭</button>
                </div>
            </div>
        `;
        
        const shortcutList = modal.querySelector('#shortcut-list');
        this.keyboardShortcuts.forEach((value, key) => {
            const item = document.createElement('div');
            item.style.cssText = `
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding: 10px 0;
                border-bottom: 1px solid #eee;
            `;
            item.innerHTML = `
                <span style="font-weight: 500;">${value.description}</span>
                <span style="
                    background: #f5f5f5;
                    padding: 5px 10px;
                    border-radius: 3px;
                    font-family: monospace;
                    font-size: 12px;
                ">${key}</span>
            `;
            shortcutList.appendChild(item);
        });
        
        document.body.appendChild(modal);
        
        // 点击背景关闭
        modal.addEventListener('click', (e) => {
            if (e.target === modal) {
                modal.remove();
            }
        });
    }

    /**
     * 设置性能优化
     */
    setupPerformanceOptimizations() {
        // 图片懒加载
        this.setupLazyLoading();
        
        // 防抖搜索
        this.setupDebouncedSearch();
        
        // 虚拟滚动（针对大数据量）
        this.setupVirtualScrolling();
        
        // 内存优化
        this.setupMemoryOptimization();
    }

    /**
     * 图片懒加载
     */
    setupLazyLoading() {
        const images = document.querySelectorAll('img[data-src]');
        const imageObserver = new IntersectionObserver((entries, observer) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    const img = entry.target;
                    img.src = img.dataset.src;
                    img.classList.remove('lazy');
                    imageObserver.unobserve(img);
                }
            });
        });

        images.forEach(img => imageObserver.observe(img));
    }

    /**
     * 防抖搜索
     */
    setupDebouncedSearch() {
        const searchInputs = document.querySelectorAll('input[type="search"], input[placeholder*="搜索"]');
        
        searchInputs.forEach(input => {
            let timeoutId;
            
            input.addEventListener('input', (e) => {
                clearTimeout(timeoutId);
                timeoutId = setTimeout(() => {
                    this.performSearch(e.target.value);
                }, 300);
            });
        });
    }

    /**
     * 虚拟滚动
     */
    setupVirtualScrolling() {
        // 为大数据量表格实现虚拟滚动
        const tables = document.querySelectorAll('table');
        
        tables.forEach(table => {
            const tbody = table.querySelector('tbody');
            if (tbody && tbody.children.length > 100) {
                this.implementVirtualScroll(tbody);
            }
        });
    }

    /**
     * 内存优化
     */
    setupMemoryOptimization() {
        // 清理未使用的监听器
        window.addEventListener('beforeunload', () => {
            this.cleanupEventListeners();
        });
        
        // 定期清理缓存
        setInterval(() => {
            this.cleanupMemory();
        }, 30000); // 每30秒清理一次
    }

    /**
     * 设置桌面增强功能
     */
    setupDesktopEnhancements() {
        // 拖拽功能
        this.setupDragAndDrop();
        
        // 右键菜单
        this.setupContextMenu();
        
        // 多选操作
        this.setupMultiSelect();
        
        // 批量操作
        this.setupBatchOperations();
    }

    /**
     * 拖拽功能
     */
    setupDragAndDrop() {
        const draggableElements = document.querySelectorAll('[draggable="true"]');
        
        draggableElements.forEach(element => {
            element.addEventListener('dragstart', (e) => {
                e.dataTransfer.setData('text/plain', element.id);
                element.classList.add('dragging');
            });
            
            element.addEventListener('dragend', () => {
                element.classList.remove('dragging');
            });
        });
        
        const dropZones = document.querySelectorAll('.drop-zone');
        
        dropZones.forEach(zone => {
            zone.addEventListener('dragover', (e) => {
                e.preventDefault();
                zone.classList.add('drag-over');
            });
            
            zone.addEventListener('dragleave', () => {
                zone.classList.remove('drag-over');
            });
            
            zone.addEventListener('drop', (e) => {
                e.preventDefault();
                zone.classList.remove('drag-over');
                const id = e.dataTransfer.getData('text/plain');
                const draggedElement = document.getElementById(id);
                zone.appendChild(draggedElement);
            });
        });
    }

    /**
     * 右键菜单
     */
    setupContextMenu() {
        document.addEventListener('contextmenu', (e) => {
            const target = e.target;
            
            // 检查是否在表格行上右键
            if (target.closest('tr')) {
                e.preventDefault();
                this.showRowContextMenu(e, target.closest('tr'));
            }
        });
        
        // 点击其他地方关闭右键菜单
        document.addEventListener('click', () => {
            this.hideContextMenu();
        });
    }

    /**
     * 多选操作
     */
    setupMultiSelect() {
        const tables = document.querySelectorAll('table');
        
        tables.forEach(table => {
            // 添加选择列
            const thead = table.querySelector('thead tr');
            if (thead && !thead.querySelector('.select-column')) {
                const th = document.createElement('th');
                th.className = 'select-column';
                th.innerHTML = '<input type="checkbox" class="select-all">';
                thead.insertBefore(th, thead.firstChild);
            }
            
            const tbody = table.querySelector('tbody');
            if (tbody) {
                const rows = tbody.querySelectorAll('tr');
                rows.forEach(row => {
                    if (!row.querySelector('.select-column')) {
                        const td = document.createElement('td');
                        td.className = 'select-column';
                        td.innerHTML = '<input type="checkbox" class="select-row">';
                        row.insertBefore(td, row.firstChild);
                    }
                });
            }
        });
        
        // 全选/取消全选
        document.addEventListener('change', (e) => {
            if (e.target.classList.contains('select-all')) {
                const table = e.target.closest('table');
                const checkboxes = table.querySelectorAll('.select-row');
                checkboxes.forEach(checkbox => {
                    checkbox.checked = e.target.checked;
                });
            }
        });
    }

    /**
     * 批量操作
     */
    setupBatchOperations() {
        // 为多选操作添加批量操作工具栏
        this.createBatchToolbar();
    }

    /**
     * 设置错误处理
     */
    setupErrorHandling() {
        // 全局错误处理
        window.addEventListener('error', (e) => {
            this.handleError(e.error || new Error(e.message));
        });
        
        // Promise rejection 处理
        window.addEventListener('unhandledrejection', (e) => {
            this.handleError(new Error(e.reason));
        });
        
        // 网络错误处理
        window.addEventListener('offline', () => {
            this.showOfflineWarning();
        });
        
        window.addEventListener('online', () => {
            this.hideOfflineWarning();
        });
    }

    /**
     * 导航到页面
     */
    navigateTo(page) {
        window.location.href = page;
    }

    /**
     * 保存当前页面
     */
    saveCurrentPage() {
        // 实现页面保存逻辑
        console.log('保存当前页面');
        this.showNotification('页面已保存', 'success');
    }

    /**
     * 聚焦搜索框
     */
    focusSearch() {
        const searchInput = document.querySelector('input[type="search"], input[placeholder*="搜索"]');
        if (searchInput) {
            searchInput.focus();
        }
    }

    /**
     * 刷新页面
     */
    refreshPage() {
        window.location.reload();
    }

    /**
     * 显示快速操作
     */
    showQuickActions() {
        // 实现快速操作面板
        console.log('显示快速操作');
    }

    /**
     * 切换侧边栏
     */
    toggleSidebar() {
        const sidebar = document.querySelector('.sidebar');
        if (sidebar) {
            sidebar.classList.toggle('collapsed');
        }
    }

    /**
     * 执行搜索
     */
    performSearch(query) {
        // 实现搜索逻辑
        console.log('搜索:', query);
    }

    /**
     * 显示通知
     */
    showNotification(message, type = 'info') {
        const notification = document.createElement('div');
        notification.className = `notification ${type}`;
        notification.innerHTML = `
            <div style="
                position: fixed;
                top: 20px;
                right: 20px;
                background: white;
                border-radius: 5px;
                padding: 15px 20px;
                box-shadow: 0 10px 30px rgba(0,0,0,0.2);
                z-index: 1001;
                animation: slideInRight 0.3s ease;
                border-left: 4px solid var(--${type}-color);
            ">
                ${message}
            </div>
        `;
        
        document.body.appendChild(notification);
        
        setTimeout(() => {
            notification.remove();
        }, 3000);
    }

    /**
     * 处理错误
     */
    handleError(error) {
        console.error('桌面端错误:', error);
        this.showNotification(`错误: ${error.message}`, 'error');
    }

    /**
     * 显示离线警告
     */
    showOfflineWarning() {
        this.showNotification('网络连接已断开，部分功能可能无法使用', 'warning');
    }

    /**
     * 隐藏离线警告
     */
    hideOfflineWarning() {
        this.showNotification('网络连接已恢复', 'success');
    }

    /**
     * 清理事件监听器
     */
    cleanupEventListeners() {
        // 清理临时事件监听器
    }

    /**
     * 清理内存
     */
    cleanupMemory() {
        // 清理临时数据
        if (window.gc) {
            window.gc();
        }
    }

    /**
     * 显示行右键菜单
     */
    showRowContextMenu(event, row) {
        // 实现行右键菜单
        console.log('显示行右键菜单', row);
    }

    /**
     * 隐藏右键菜单
     */
    hideContextMenu() {
        // 隐藏右键菜单
    }

    /**
     * 创建批量操作工具栏
     */
    createBatchToolbar() {
        // 实现批量操作工具栏
    }

    /**
     * 实现虚拟滚动
     */
    implementVirtualScroll(container) {
        // 实现虚拟滚动逻辑
    }
}

/**
 * 性能监控类
 */
class PerformanceMonitor {
    constructor() {
        this.metrics = new Map();
        this.startTime = performance.now();
        this.init();
    }

    init() {
        this.monitorMemory();
        this.monitorFPS();
        this.monitorNetwork();
    }

    monitorMemory() {
        setInterval(() => {
            if (performance.memory) {
                const memory = performance.memory;
                this.metrics.set('memory', {
                    used: memory.usedJSHeapSize,
                    total: memory.totalJSHeapSize,
                    limit: memory.jsHeapSizeLimit
                });
            }
        }, 5000);
    }

    monitorFPS() {
        let frameCount = 0;
        let lastTime = performance.now();
        
        const checkFPS = () => {
            frameCount++;
            const currentTime = performance.now();
            
            if (currentTime - lastTime >= 1000) {
                const fps = Math.round((frameCount * 1000) / (currentTime - lastTime));
                this.metrics.set('fps', fps);
                
                frameCount = 0;
                lastTime = currentTime;
                
                // 如果FPS过低，发出警告
                if (fps < 30) {
                    console.warn(`低FPS警告: ${fps}`);
                }
            }
            
            requestAnimationFrame(checkFPS);
        };
        
        checkFPS();
    }

    monitorNetwork() {
        // 监控网络状态
        window.addEventListener('online', () => {
            this.metrics.set('online', true);
        });
        
        window.addEventListener('offline', () => {
            this.metrics.set('online', false);
        });
    }

    getMetrics() {
        return Object.fromEntries(this.metrics);
    }
}

// 初始化桌面端优化器
document.addEventListener('DOMContentLoaded', () => {
    window.desktopOptimizer = new DesktopOptimizer();
});

// 导出到全局作用域
window.DesktopOptimizer = DesktopOptimizer;